<?php

namespace App\Services;

use App\Models\Company;
use App\Models\CompanyUser;
use App\Models\Department;
use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class CompanyService extends BaseService
{
    /**
     * 获取公司下的部门
     */
    public function getDepartments($companyId)
    {
        if (!$companyId) {
            $companyId = company_id();
        }
        $list = Department::query()->where('company_id', $companyId)->select('id', 'title')->get();

        return $list->isNotEmpty() ? $list->toArray() : [];
    }

    /**
     * 获取数据列表
     */
    public function getList($request, $perPage)
    {
        $thisQuery = Company::query()->with('principal')->orderByDesc('id');

        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $thisQuery->where('title', 'like', $keyword)->orWhere('certificate', 'like', $keyword);
        }
        $list = $thisQuery->paginate($perPage);
        if ($list->isEmpty()) return [];

        $list = $list->toArray();

        foreach ($list['data'] as &$val) {
            $val['created_at'] = date('Y-m-d', strtotime($val['created_at']));
        }

        return $this->removeNoUsedPageParams($list);
    }

    /**
     * 获取一条公司记录
     */
    public function getInfo($id)
    {
        return Company::query()->where('id', $id)->first();
    }

    /**
     * 公司编辑
     */
    public function updateData($id, $params)
    {
        DB::beginTransaction();
        try {
            $companyInfo = Company::query()->where('id', $id)->first();
            if (!in_array($params['status'], [0, 1, 2])) {
                throw new Exception('审核状态参数不正确');
            }
            $company = Company::query()->where('id', $id)->first();
            $company->title  = $params['title'];
            $company->status = $params['status'];
            $company->certificate = $params['certificate'];
            $company->fonds_number = $params['fonds_number'];
            $company->save();

            $companyRole = Role::query()->where('company_id', $id)->first();

            if (empty($companyRole) && !$companyInfo->status && $params['status'] == 1) { //在编辑里面首次通过
                self::addCompanyRoles($id); //公司首次通过，给公司新增一个管理员和副管理员
            }
            DB::commit();
            return ['msg' => ''];
        }
        catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 登录页面 新增公司
     */
    public function storeCompanyByUser($params, $userId)
    {
        DB::beginTransaction();
        try {
            $info = Company::query()
                ->where('title', $params['title'])
                ->where('certificate', $params['certificate'])
                ->first();
            if ($info) {
                throw new Exception('该公司名称已存在！');
            }
            $company = new Company();
            $company->title       = $params['title'];
            $company->certificate = $params['certificate'];
            $company->fonds_number = $params['fonds_number'] ?? '';
            $company->status      = 0; //待审核
            $company->auth_book   = $params['auth_book'] ?? '';
            $company->creator_id  = user_id();
            $company->save();

            $companyUser = new CompanyUser();
            $companyUser->company_id = $company->id;
            $companyUser->user_id    = $userId;
            $companyUser->role_id    = 1; //先存为0，通过后更改为1
            $companyUser->is_admin   = 1;
            $companyUser->creator_id = user_id();
            $companyUser->save();

            CommonService::addActionLog("新增一个公司：{$params['title']}");
            DB::commit();

            return ['msg' => ''];
        }
        catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 公司审核通过或拒绝
     */
    public function audit($companyId, $status)
    {
        try {
            if (!in_array($status, [0, 1, 2])) {
                throw new Exception('审核状态参数不正确');
            }
            $company = Company::query()->with('principal')->find($companyId);
            if ($company->status > 0) {
                throw new Exception('已审核，无法重新审核');
            }
            Company::query()->where('id', $companyId)->update(['status' => $status]);
            if ($status == 1) { //如果通过
                self::addCompanyRoles($companyId);
                CommonService::addActionLog("公司审核通过", "数据ID:{$companyId}");
                DB::commit();
                return ['msg' => ''];
            }
        }
        catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 审核通过后在角色表添和副管理员
     * admin_level : 0非管理员;1超管,2公司管理员,3副管理员
     */
    public static function addCompanyRoles($companyId)
    {
        $manageUser = CompanyUser::query() //公司关联用户表的管理员改为已通过
            ->where('company_id', $companyId)
            ->where('is_admin', 1)
            ->first();

        User::query()->where('id', $manageUser['user_id'])->update(['status' => 1]);

        if (!Role::query()->where('company_id', $companyId)->where('title', '公司管理员')->first()) {
            $role1 = new Role(); //创建公司管理员
            $role1->company_id  = $companyId;
            $role1->title       = '公司管理员';
            $role1->menu_ids    = config('site.company_admin_menus'); //初始化管理员权限
            $role1->admin_level = 2;
            $role1->status      = 1;
            $role1->creator_id  = user_id();
            $role1->save();
            $manageUser->role_id = $role1->id;
            $manageUser->save();
        }

        if (!Role::query()->where('company_id', $companyId)->where('title', '副管理员')->first()) {
            $role2 = new Role(); //创建公司副管理员
            $role2->company_id  = $companyId;
            $role2->title       = '副管理员';
            $role2->menu_ids    = config('site.company_admin_menus'); //初始化权限，和公司管理员一样
            $role2->admin_level = 3;
            $role2->status      = 1;
            $role2->creator_id  = user_id();
            $role2->save();
        }

        if (!Role::query()->where('company_id', $companyId)->where('title', '档案员')->first()) {
            $role3 = new Role(); //创建归档员
            $role3->company_id  = $companyId;
            $role3->title       = '档案员';
            $role3->menu_ids    = config('site.archivist_menus'); //初始化权限,项目管理，操作记录
            $role3->admin_level = 0;
            $role3->status      = 1;
            $role3->creator_id  = user_id();
            $role3->save();
        }

    }

    /**
     * 返回公司下的用户列表
     */
    public function users(int $companyId)
    {
        $company = Company::query()->with('users:id,nickname,status')->find($companyId);

        if (!$company) return [];

        return $company->users->toArray();
    }

    /**
     * 给公司下的员工授权
     */
    public function auth($companyId, $userId, $roleIds)
    {
        try {
            foreach ($roleIds as $roleId) {
                $info = CompanyUser::query()
                    ->where('company_id', $companyId)
                    ->where('user_id', $userId)
                    ->where('role_id', $roleId)
                    ->first();

                if (!empty($info)) { //如果之前给过角色
                    if (!$info->status) { //如果已禁用
                        $info->status = 1; //重新启用
                        $info->save();
                    }
                } else { //如果还没有过这个角色，新增记录
                    $companyUser = new CompanyUser();
                    $companyUser->company_id = $companyId;
                    $companyUser->user_id = $userId;
                    $companyUser->role_id = $roleId;
                    $companyUser->status = 1;
                    $companyUser->creator_id = user_id();
                    $companyUser->save();
                }
            }
            return ['msg' => ''];
        }
        catch (Exception $exception) {
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 返回公司下的用户和用户角色
     */
    public function userRoles(int $companyId)
    {
        return Company::query()->with('users.roles')->find($companyId);
    }

    /**
     * 回收站列表
     */
    public function getRecycles($request): array
    {
        $thisQuery = Company::onlyTrashed();

        if ($request->filled('keyword')) { //判断参数是否存在并且不为空
            $keyword = $request->input('keyword'); //由于不同的表字段不同，所以单独拿出来
            $thisQuery->where('title', 'like', "%{$keyword}%")->orWhere('id', '=', $keyword);
        }

        return $this->formatRecycleData($request, $thisQuery);
    }

    /**
     * 是否是公司管理员
     */
    public static function isCompanyAdminer($companyId, $userId)
    {
        return CompanyUser::query()->where(['company_id' => $companyId, 'user_id' => $userId])->value('is_admin');
    }

}
